﻿using MediatR;
using Process.Api.Application.Command;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler
{
    public class DetailProcessFlowHandler : IRequestHandler<DetailProcessFlowCommand, ApiResult<ProcessFlow>>
    {
        private readonly IProcessRepository<ProcessFlow> _processFlowRepo;
        private readonly IProcessRepository<FlowProcessRelation> _processRelationRepo;
        private readonly IProcessRepository<Processinfo> _processinfoRepo;
        private readonly ILogger<DetailProcessFlowHandler> _logger;

        public DetailProcessFlowHandler(IProcessRepository<ProcessFlow> processFlowRepo, IProcessRepository<FlowProcessRelation> processRelationRepo, IProcessRepository<Processinfo> processinfoRepo, ILogger<DetailProcessFlowHandler> logger)
        {
            _processFlowRepo = processFlowRepo;
            _processRelationRepo = processRelationRepo;
            _processinfoRepo = processinfoRepo;
            _logger = logger;
        }
        /// <summary>
        /// 查看工艺流程详情
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<ProcessFlow>> Handle(DetailProcessFlowCommand request, CancellationToken cancellationToken)
        {
           var result = new ApiResult<ProcessFlow>();

            // 1) 基本信息
            var flow = _processFlowRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && !x.IsDelete);
            if (flow == null)
            {
                result.Code = ErrorStatus.Error;
                result.Message = "未找到工艺流程";
                result.Data = null;
                return Task.FromResult(result);
            }

            // 2) 取出关联关系并按排序
            var relations = _processRelationRepo
                .GetAllAsync()
                .Where(x => x.ProcessFlowId == flow.Id && !x.IsDelete)
                .OrderBy(x => x.Sort)
                .ToList();

            // 3) 一次性取出涉及到的工序，填充到关系的导航属性上，便于前端展示负责人、部门等
            if (relations.Any())
            {
                var processIds = relations.Select(x => x.ProcessId).Distinct().ToList();
                var processes = _processinfoRepo.GetAllAsync()
                    .Where(p => processIds.Contains(p.Id) && !p.IsDelete)
                    .ToList();
                var procMap = processes.ToDictionary(p => p.Id, p => p);

                foreach (var rel in relations)
                {
                    if (procMap.TryGetValue(rel.ProcessId, out var proc))
                    {
                        rel.Process = proc; // 包含 processCode、processName、responsible、department、remark
                    }
                }
            }

            // 4) 回填集合，返回
            flow.FlowProcessRelations = relations;

            result.Code = ErrorStatus.Success;
            result.Message = "获取成功";
            result.Data = flow;
            return Task.FromResult(result);
        }
    }
}
